﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using Meraz.Core.Repositories;

namespace Meraz.Core.Commands
{
    public interface ISaveUrlRedirectCommand :ICommand<UrlRedirect>{
        string Redirect { get; set; }
        string Destination { get; set; }
        IUrlRedirectRepository Repository { get; set; }
    }
    public class SaveUrlRedirectCommand : BaseCommand, ISaveUrlRedirectCommand
    {
        public SaveUrlRedirectCommand(IUrlRedirectRepository repository)
        {
            Repository = repository ?? new UrlRedirectRepository();
        }
        public string Redirect { get; set; }
        public string Destination { get; set; }
        public IUrlRedirectRepository Repository { get; set; }
        public UrlRedirect Result { get; set; }
        public void Execute()
        {
            if (string.IsNullOrWhiteSpace(Redirect) || string.IsNullOrWhiteSpace(Destination))
                throw new ApplicationException("Invalid redirect or destination");
            UrlRedirect urlRedirect = Repository.GetByUrl(Redirect);
            if (urlRedirect == null)
            {
                urlRedirect = new UrlRedirect();
                Repository.Add(urlRedirect);
                urlRedirect.Start = Redirect;
                urlRedirect.Finish = Destination;
            }
            else
            {
                urlRedirect.Finish = Destination;
            }
            Commit();
            Result = urlRedirect;
        }
    }
}
